package com.atguigu.yygh.order.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.atguigu.yygh.common.R;
import com.atguigu.yygh.common.Result;
import com.atguigu.yygh.common.ResultCodeEnum;
import com.atguigu.yygh.common.handler.YyghException;
import com.atguigu.yygh.enums.PaymentTypeEnum;
import com.atguigu.yygh.enums.RefundStatusEnum;
import com.atguigu.yygh.model.order.OrderInfo;
import com.atguigu.yygh.model.order.PaymentInfo;
import com.atguigu.yygh.model.order.RefundInfo;
import com.atguigu.yygh.order.service.OrderService;
import com.atguigu.yygh.order.service.PaymentService;
import com.atguigu.yygh.order.service.RefundInfoService;
import com.atguigu.yygh.order.service.WeixinService;
import com.atguigu.yygh.order.utils.ConstantPropertiesUtils;
import com.atguigu.yygh.order.utils.HttpClient;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.github.wxpay.sdk.WXPayConstants;
import com.github.wxpay.sdk.WXPayUtil;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import io.swagger.models.auth.In;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@Service
public class WeixinServiceImpl implements WeixinService {

    @Autowired
    private OrderService orderService;
    @Autowired
    private PaymentService paymentService;
    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private RefundInfoService refundInfoService;
    /**
     * 根据订单号下单，生成支付链接
     */
    @Override
    public Map createNative(Long orderId) {
        try {
            Map payMap = (Map) redisTemplate.opsForValue().get(orderId.toString());
            if(null != payMap) return payMap;
            //1、根据orderId查询订单信息
            OrderInfo orderInfo = orderService.getById(orderId);
            //2、根据交易类型，保存交易记录
            paymentService.savePaymentInfo(orderInfo, PaymentTypeEnum.WEIXIN.getStatus());
            //3、设置参数，封装调用微信接口参数
            Map paramMap = new HashMap();
            paramMap.put("appid", ConstantPropertiesUtils.APPID);   //公众号id
            paramMap.put("mch_id", ConstantPropertiesUtils.PARTNER);   //商户id
            paramMap.put("nonce_str", WXPayUtil.generateNonceStr());
            String body = orderInfo.getReserveDate() + "就诊"+ orderInfo.getDepname();
            paramMap.put("body", body);
            paramMap.put("out_trade_no", orderInfo.getOutTradeNo());
            //paramMap.put("total_fee", orderInfo.getAmount().multiply(new BigDecimal("100")).longValue()+"");
            paramMap.put("total_fee", "1");//为了测试
            paramMap.put("spbill_create_ip", "127.0.0.1");   //终端ip
            paramMap.put("notify_url", "http://guli.shop/api/order/weixinPay/weixinNotify");  //回调地址
            paramMap.put("trade_type", "NATIVE");  //类型
            //4、创建客户都安对象（url），HTTPClient来根据URL访问第三方接口并且传递参数
            HttpClient client = new HttpClient("https://api.mch.weixin.qq.com/pay/unifiedorder");  //统一下单url
            //5、向客户都安对象存入参数（map=>xml）
            //  使用client设置参数
            client.setXmlParam(WXPayUtil.generateSignedXml(
                    paramMap,
                    ConstantPropertiesUtils.PARTNERKEY //使用商户id确认
            ));
            // https是加密，打开开关:
            client.setHttps(true);
            //6、客户都安对象发送请求
            client.post();
            //7、获取响应（xml类型），转换类型（xml=>map）   返回第三方的数据
            String xml = client.getContent();  //注意此时返回的是xml类型
            System.out.println("xml = " + xml);
            Map<String, String> resultMap = WXPayUtil.xmlToMap(xml); //xml转map
            //8、封装返回结果集（只要关键信息）
            Map map = new HashMap<>();
            map.put("orderId", orderId);
            map.put("totalFee", orderInfo.getAmount());
            map.put("resultCode", resultMap.get("result_code"));
            map.put("codeUrl", resultMap.get("code_url"));
            if(null != resultMap.get("result_code")) {
                //微信支付二维码2小时过期，可采取2小时未支付取消订单
                redisTemplate.opsForValue().set(orderId.toString(), map, 1000, TimeUnit.MINUTES);
            }
            return map;
        } catch (Exception e) {
            e.printStackTrace();
            return new HashMap<>();
        }
    }

    /**
     * 查询交易状态
     * 根据orderId订单号、支付类型调用接口方法，获取交易结果
     * @param orderId 订单Id
     * @param paymentType 支付类型（1,支付宝  2,微信）
     * @return
     */
    @Override
    public Map<String, String> queryPayStatus(Long orderId, Integer paymentType) {
        try {
            //1、根据orderId、支付类型查询交易记录
            /*QueryWrapper<PaymentInfo> wrapper = new QueryWrapper<>();
            wrapper.eq("order_id",orderId);
            wrapper.eq("payment_type",paymentType);  //交易类型
            PaymentInfo paymentInfo = paymentService.getOne(wrapper);*/
            PaymentInfo paymentInfo = paymentService.getPaymentInfo(orderId,paymentType);
            if (paymentInfo == null) {
                throw new YyghException(20001,"交易记录有误！");
            }
            //2、封装调用微信接口参数
            Map paramMap = new HashMap<>();
            paramMap.put("appid", ConstantPropertiesUtils.APPID);
            paramMap.put("mch_id", ConstantPropertiesUtils.PARTNER);
            paramMap.put("out_trade_no", paymentInfo.getOutTradeNo());
            paramMap.put("nonce_str", WXPayUtil.generateNonceStr());
            //3、创建客户都安对象（url）
            HttpClient client = new HttpClient("https://api.mch.weixin.qq.com/pay/orderquery"); //查询订单url
            //4、向客户都安对象存入参数（map=>xml）
            client.setXmlParam(WXPayUtil.generateSignedXml(paramMap, ConstantPropertiesUtils.PARTNERKEY));
            client.setHttps(true);
            //5、客户都安对象发送请求
            client.post();
            //6、获取响应（xml），转换类型（xml=>map）
            String xml = client.getContent();
            System.out.println("查询交易xml = " + xml);
            Map<String, String> resultMap = WXPayUtil.xmlToMap(xml);
            //7、返回
            return resultMap;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    /***
     * 退款
     * @param orderId 订单id
     * @return
     */
    @Override
    public Boolean refund(Long orderId) {
        try {
            //1、根据参数查询交易记录
            PaymentInfo paymentInfoQuery = paymentService.getPaymentInfo(orderId, PaymentTypeEnum.WEIXIN.getStatus());
            //2、根据交易记录保存退款记录，并获取
            RefundInfo refundInfo = refundInfoService.saveRefundInfo(paymentInfoQuery);
            //  2.1、判断退款状态：1，退款中 2，已退款
            if(refundInfo.getRefundStatus().intValue() == RefundStatusEnum.REFUND.getStatus().intValue()) {
                return true;
            }
            //3、封装调用微信接口参数
            Map<String,String> paramMap = new HashMap<>(8);
            paramMap.put("appid",ConstantPropertiesUtils.APPID);       //公众账号ID
            paramMap.put("mch_id",ConstantPropertiesUtils.PARTNER);   //商户编号
            paramMap.put("nonce_str",WXPayUtil.generateNonceStr());
            paramMap.put("transaction_id",paymentInfoQuery.getTradeNo()); //微信订单号
            paramMap.put("out_trade_no",paymentInfoQuery.getOutTradeNo()); //商户订单编号
            paramMap.put("out_refund_no","tk"+paymentInfoQuery.getOutTradeNo()); //商户退款单号
            //       paramMap.put("total_fee",paymentInfoQuery.getTotalAmount().multiply(new BigDecimal("100")).longValue()+"");
            //       paramMap.put("refund_fee",paymentInfoQuery.getTotalAmount().multiply(new BigDecimal("100")).longValue()+"");
            paramMap.put("total_fee","1");    //总费用
            paramMap.put("refund_fee","1");  //退款手续费
            //4、创建客户端对象（url）
            HttpClient client = new HttpClient("https://api.mch.weixin.qq.com/secapi/pay/refund");
            //5、向客户端对象存入参数（map=>xml）
            String paramXml = WXPayUtil.generateSignedXml(paramMap,ConstantPropertiesUtils.PARTNERKEY);
            client.setXmlParam(paramXml);
            client.setHttps(true);
            //6、设置证书相关参数
            client.setCert(true);  //开启证书
            client.setCertPassword(ConstantPropertiesUtils.PARTNER);  //证书密码（商户号）
            //7、客户端对象发送请求
            client.post();
            //8、返回第三方的数据，获取响应（xml），转换类型（xml=>map）
            String xml = client.getContent();
            System.out.println("退款xml = " + xml);
            Map<String, String> resultMap = WXPayUtil.xmlToMap(xml);
            //9、判断是否成功。更新退款记录
            if (null != resultMap && WXPayConstants.SUCCESS.equalsIgnoreCase(resultMap.get("result_code"))) {
                refundInfo.setCallbackTime(new Date());  //回调时间
                refundInfo.setTradeNo(resultMap.get("refund_id"));  //退款id（交易编号）
                refundInfo.setRefundStatus(RefundStatusEnum.REFUND.getStatus());    //退款状态
                refundInfo.setCallbackContent(JSONObject.toJSONString(resultMap));   //回调信息  报文
                refundInfoService.updateById(refundInfo);    //更新数据
                return true;
            }
            return false;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }

}
